package com.clps.rulesregulations.controller;

import com.clps.rulesregulations.domain.User;
import com.clps.rulesregulations.form.LoginForm;
import com.clps.rulesregulations.service.UserService;
import com.clps.rulesregulations.util.Const;
import com.clps.rulesregulations.util.ResultView;
import com.clps.rulesregulations.util.ValidateCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * 公共控制类
 *
 * @author zhangchao
 * @date 2018-11-06
 */
@Controller
public class CommonController {
    @Autowired
    private UserService userService;
    @RequestMapping("/validateCode")
    public void validateCode(HttpSession session, HttpServletResponse response) throws IOException {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        ValidateCode vCode = new ValidateCode(120, 40, 4, 0);
        session.setAttribute(Const.VALIDATECODE, vCode.getCode());
        vCode.write(response.getOutputStream());
    }
    @RequestMapping(value = {"","/"})
    public String index(){
        return "regulation/search";
    }
    @RequestMapping(value ="/index")
    public String index2(){
        return "index";
    }
    /**
     * 去登录
     * @return
     */
    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    /**
     * 去登录
     * @return
     */
    @GetMapping("/loginguest")
    public String loginguest(){
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        String username = "Guest";
        String password = "123456";
        User user = userService.findUserByUsername(username);
        if(user==null) throw new UnknownAccountException();
        if (0==user.getEnable()) {
            throw new LockedAccountException(); // 帐号锁定
        }

        //更新最后登录时间
        user.setLastLoginTime(new Date());
        userService.updateUser(user);
        // 当验证都通过后，把用户信息放在session里
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("userSession", user);
        session.setAttribute("userSessionId", user.getId());
        session.setAttribute(Const.VALIDATECODE,new Date()+"");
        // 身份验证
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);
            resultView.setMsg("登录成功");
        }catch (UnknownAccountException e){
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("用户名不存在");
        }catch (IncorrectCredentialsException e) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("密码错误");
        }catch (Exception e) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("用户名或密码错误");
        }
        return "regulation/search";
    }

    /**
     * 登录
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResultView login(@RequestBody LoginForm loginForm, HttpSession session)throws Exception {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        String username = loginForm.getUsername();
        String password = loginForm.getPassword();
        String code = loginForm.getValidatecode();

        String validatecode = (String)session.getAttribute(Const.VALIDATECODE);
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("请输入用户名或密码");
            return resultView;
        }else if(StringUtils.isBlank(validatecode)){
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("验证码不能为空");
            return resultView;
        }else if(!validatecode.equalsIgnoreCase(code)){
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("验证码错误");
            return resultView;
        }

        session.setAttribute(Const.VALIDATECODE,new Date()+"");
        // 身份验证
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);
            resultView.setMsg("登录成功");
        }catch (UnknownAccountException e){
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("用户名不存在");
        }catch (IncorrectCredentialsException e) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("密码错误");
        }catch (Exception e) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("用户名或密码错误");
        }

        return resultView;
    }
    @RequestMapping("/403")
    public String unauthorizedRole(){
        return "403";
    }
}
